<template>
  <div class="chat-container">
    <h2>智能助手</h2>
    <div class="response-box" ref="responseBox">
      <vue-markdown :source="currentResponse"></vue-markdown>
<!--      <div class="response-text">{{ currentResponse }}</div>-->
    </div>
    <div class="input-box">
      <input
          type="text"
          v-model="userInput"
          placeholder="请输入您的问题..."
          @keypress.enter="sendMessage"
          class="user-input"
      />
      <button @click="sendMessage">发送</button>
    </div>
  </div>
</template>

<script>
import VueMarkdown from 'vue-markdown'
export default {
  components: {
    'vue-markdown': VueMarkdown
  },

  data() {
    return {
      ws: null, // WebSocket 实例
      userInput: "", // 用户输入
      currentResponse: "", // 当前响应内容
    };
  },
  mounted() {
    // 初始化 WebSocket 连接
    this.ws = new WebSocket("ws://localhost:8080/chat");

    // 监听 WebSocket 消息
    this.ws.onmessage = (event) => {
      if (event.data === "[END]") {
        this.currentResponse += "\n\n";
        this.scrollToBottom();
      } else {
        this.currentResponse += event.data;
        this.scrollToBottom();
      }
    };

    // 监听 WebSocket 错误
    this.ws.onerror = (error) => {
      console.error("WebSocket 错误:", error);
    };
  },
  methods: {
    // 发送消息
    sendMessage() {
      if (this.userInput.trim()) {
        this.ws.send(this.userInput.trim());
        this.userInput = "";
        this.currentResponse = "正在思考...\n";
      }
    },
    // 滚动到底部
    scrollToBottom() {
      this.$nextTick(() => {
        const responseBox = this.$refs.responseBox;
        responseBox.scrollTop = responseBox.scrollHeight;
      });
    },
  },
  beforeDestroy() {
    // 组件销毁时关闭 WebSocket 连接
    if (this.ws) {
      this.ws.close();
    }
  },
};
</script>

<style scoped>
/* 样式仅作用于当前组件 */
.chat-container {
  font-family: Arial, sans-serif;
  max-width: 1000px;
  margin: 20px auto;
  padding: 20px;
  border: 1px solid #ddd;
  border-radius: 8px;
}

.response-box {
  height: 550px;
  overflow-y: auto;
  border: 1px solid #eee;
  padding: 15px;
  margin: 10px 0;
  background: #f9f9f9;
}

.response-text {
  white-space: pre-wrap;
  line-height: 1.6;
}

.input-box {
  display: flex;
  gap: 10px;
  height: 40px;
}

.user-input {
  flex: 1;
  padding: 8px;
  border: 1px solid #ddd;
  border-radius: 4px;
}

button {
  padding: 8px 20px;
  background: #007bff;
  color: white;
  border: none;
  border-radius: 4px;
  cursor: pointer;
}

button:hover {
  background: #0056b3;
}
</style>